package com.leetcode.string;

import java.util.LinkedList;

public class SimplifyPath {

    public static void main(String[] args) {
        String path = "/a//b////c/d//././/..";
        SimplifyPath simplifyPath = new SimplifyPath();
        System.out.println(simplifyPath.simplifyPath(path));
    }
    public String simplifyPath(String path) {
        int len = path.length();
        int ind = 1;
        StringBuilder sb = new StringBuilder();
        LinkedList<String> stack = new LinkedList<>();
        stack.push("/");
        while(ind < len) {
            char ch = path.charAt(ind++);
            if (ch != '/') {
                sb.append(ch);
                continue;
            }
            if (sb.toString().isEmpty() && !stack.isEmpty() && stack.peek().equals("/")) {
                continue;
            }
            if (sb.toString().equals("..")) {
                if (stack.size() > 1) {
                    stack.pop();
                    stack.pop();
                }
                sb.delete(0, 2);
                continue;
            }
            if (sb.toString().equals(".")) {
                sb.delete(0, 1);
                continue;
            }
            stack.push(sb.toString());
            stack.push("/");
            sb.delete(0, sb.length());
        }
        if (sb.toString().equals("..")) {
            if (stack.size() > 1) {
                stack.pop();
                stack.pop();
            }
            sb.delete(0, 2);
        }
        if (sb.toString().equals(".")) {
            sb.delete(0, 1);
        }
        if (!sb.toString().isEmpty()) {
            stack.push(sb.toString());
        }
        if (stack.size() > 1 && stack.peek().equals("/")) {
            stack.pop();
        }
        String res = "";
        while(!stack.isEmpty()) {
            res = stack.pop() + res;
        }
        return res;
    }
}
